<link rel="stylesheet" href="/js/jquery-confirm/jquery-confirm.min.css">
<link rel="stylesheet" href="/css/upload.css">

<div id="mainUploadBox" class="upload-wrap">
    <div class="image-item" v-for="(item, index) in imageList" :key="index">
        <img :src="item.path" class="item-img"/>
        <div class="item-handle-mask">
            <span class="glyphicon glyphicon-eye-open" aria-hidden="true" v-on:click="previewImage(item)"></span>
            <span class="glyphicon glyphicon-trash" aria-hidden="true" v-on:click="removeImage(index)"></span>
        </div>
    </div>
    <div id="upload-box-main" class="not-draggable" v-if="imageList.length < limit">
        <input type="file" id="file-input-main" style="display:none;" accept="image/*" multiple v-on:change="fileUpload"/>
        <label for="file-input-main" class="file-button">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
            <span style="margin-top:10px">上传图片</span>
        </label>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="mainImageModal" tabindex="-1" role="dialog" aria-labelledby="mainModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="mainModalLabel">预览图片</h4>
                </div>
                <div class="modal-body">
                    <img :src="previewImageSrc" style="display:block;width:100%;"/>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/js/vue/vue-2.7.js"></script>
<script src="/js/sortable/Sortable.min.js"></script>
<script src="/js/jquery-confirm/jquery-confirm.min.js"></script>
<script src="/js/compressor/compressor.min.js"></script>
<script src="/js/compressor/compressorUtil.js"></script>
<script src="/js/utils/ajaxFunc.js"></script>
<script>
    const mainImgStr = '{{ $mainImgStr ?? '' }}';

    $(function() {
        let mainVm = new Vue({
            el: '#mainUploadBox',
            data: {
                // 图片列表
                imageList: [],
                // 上传数量限制
                limit: 10,
                // 预览图片
                previewImageSrc: '',
            },
            methods: {
                // 图片上传
                async fileUpload (e) {
                    let files = e.target.files
                    let formData = new FormData();
                    for(let i = 0; i < files.length; i++) {
                        formData.append(`file[${i}]`, await compressImage(files[i]));
                    }
                    formData.append('_token', $("input[name='_token']").val());
                    ajaxFileFunc('/admin/upload/multiple', formData, {}, res => {
                        res.map(v => {
                            mainVm.imageList.push({
                                id: v,
                                path: getImgUrlFunc(v)
                            })
                        })
                        mainVm.imgIdPush()
                    })
                },
                // 图片id传递
                imgIdPush() {
                    let imgIds = [];
                    mainVm.imageList.map(item => {
                        imgIds.push(item.id)
                    })
                    $("input[name='main_img_ids']").val(imgIds.join(','))
                },
                // 删除图片
                removeImage(index) {
                    $.confirm({
                        title: '温馨提示',
                        content: '确认要删除该图片吗？',
                        buttons: {
                            '取消': function () {},
                            '确认': function () {
                                mainVm.imageList.splice(index, 1)
                                mainVm.imgIdPush()
                            }
                        }
                    });
                },
                // 预览图片
                previewImage(row) {
                    mainVm.previewImageSrc = row.path
                    $('#mainImageModal').modal('toggle')
                }
            },
            mounted() {
                let hrefArr = window.location.href.split('?')[0].split('/');
                if(hrefArr[hrefArr.length-1] === 'create') {
                    // 新增

                } else {
                    // 编辑
                    let imgIds = []
                    if($("input[name='main_img_ids']").val()) {
                        imgIds = $("input[name='main_img_ids']").val().split(',');
                    } else if(mainImgStr) {
                        imgIds = mainImgStr.split(',');
                    }
                    setTimeout(() => {
                        imgIds.map(item => {
                            mainVm.imageList.push({
                                id: item,
                                path: getImgUrlFunc(item)
                            })
                        })
                        mainVm.imgIdPush()
                    }, 1000);
                }
                setTimeout(() => {
                    mainSortableInit()
                }, 1000);
            }
        })
        // 拖动排序
        function mainSortableInit() {
            let el = document.getElementById('mainUploadBox');

            let mainsort = new Sortable.create(el, {
                animation: 150,
                ghostClass: 'sortable-ghost', // 添加拖动时的样式
                draggable: ".image-item",
                filter: '.not-draggable',
                ignoreFrom: '.not-draggable',
                onEnd: function({ oldIndex, newIndex }) {
                    // 使用Vue的数组操作方法进行排序
                    let currentList = [...mainVm.imageList]
                    const movedItem = currentList.splice(oldIndex, 1)[0]; // 移除旧位置的元素
                    currentList.splice(newIndex, 0, movedItem); // 插入到新位置
                    mainVm.imageList = []
                    setTimeout(() => {
                        mainVm.imageList = [...currentList]
                        // 如果imgIdPush是一个需要在排序后调用的方法，确保它能正确工作
                        mainVm.imgIdPush();
                    });
                }
            });
        }
    })
</script>
